package com.duan.laugh.sms.core;

import com.duan.laugh.common.core.annotation.BeanAlias;
import com.duan.laugh.sms.core.exception.SmsChannelNotFoundException;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 短信渠道工厂
 *
 * @author duanjw
 */
public class SmsChannelFactory {
    private Map<String, SmsChannel> smsChannelMap = new HashMap<>(3);

    /**
     * 初始化所有短信渠道
     *
     * @param smsChannels
     */
    public SmsChannelFactory(List<SmsChannel> smsChannels) {
        smsChannels.forEach(smsChannel -> {
            // 有别名使用别名，否则使用类名
            String name = Optional.ofNullable(AnnotationUtils.findAnnotation(smsChannel.getClass(), BeanAlias.class)).map(item -> item.value()).orElse(smsChannel.getClass().getSimpleName());
            smsChannelMap.put(name, smsChannel);
        });
    }

    /**
     * 根据key获取短信渠道
     *
     * @param key
     * @return
     */
    public SmsChannel getSmsChannel(String key) {
        // 如果取不到对应渠道，抛出短信渠道不存在异常
        return Optional.ofNullable(smsChannelMap.get(key)).orElseThrow(SmsChannelNotFoundException::new);
    }

}
